package com.jye.rseven.user.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jye.rseven.Constants.MyConstants;
import com.jye.rseven.domain.*;
import com.jye.rseven.service.PaymentService;
import com.jye.rseven.service.PtInfoService;
import com.jye.rseven.service.TyPtCodeService;
import com.jye.rseven.service.TzPtCodeService;
import com.jye.rseven.user.util.OrderCodeFactory;
import com.jye.rseven.user.util.queue.DelayOrderService;
import com.jye.rseven.user.util.queue.ItemDelayed;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/ptInfo")
@Api(tags="拼团订单API")
public class PtInfoController {

    @Reference
    PtInfoService ptInfoService;

    @Reference
    TyPtCodeService tyPtCodeService;

    @Reference
    TzPtCodeService tzPtCodeService;

    @Reference
    PaymentService paymentService;

    @Reference
    DelayOrderService delayOrderService;

    @PostMapping("/addTzPtInfo")
    @ApiOperation(value="添加团长拼团订单", notes="新增团长订单的时候，同时在团长表记录团长信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "PtInfo",
                    value = "拼团订单实体类", required = true,
                    dataType = "com.jye.rseven.user.domain.PtInfo"),
    })
    public JsonResult addTzPtGoods(PtInfo ptInfo,String status) {
        OrderCodeFactory orderCodeFactory = new OrderCodeFactory();
        String pid = orderCodeFactory.getOrderCode(ptInfo.getUId()); //订单编号
        String ptCode = orderCodeFactory.getCombinationOrder(ptInfo.getUId()); //团单编号
        JsonResult jsonResult = new JsonResult();
        Payment payment = new Payment();//status
        String type = MyConstants.paymentType.pintuan;
        payment.setStatus(status);
        payment.setType(type);
        payment.setOrderId(ptInfo.getPtGoodsId());
        payment.setUId(ptInfo.getUId());
        payment.setPId(pid);
        payment.setTotalPrice(BigDecimal.valueOf(ptInfo.getPrice()));
        payment.setSubject(ptInfo.getName());

            if (status.equals(MyConstants.payStatus.paid))
            {
                if (paymentService.addPay(payment) != 0){
                    ptInfo.setPtCode(ptCode);//生成团id
                    ptInfo.setPtOrderCode(pid);//生成订单id
                    int is = MyConstants.ptHeader.header;//设置为团长
                    ptInfo.setIsHeader(is);
                    int i = ptInfoService.addPtInfo(ptInfo);
                    if (i == 1) {
                        TzPtCode tz = new TzPtCode();
                        tz.setPtStatus(MyConstants.ptStatus.doing);
                        tz.setUId(ptInfo.getUId());
                        tz.setPtCode(ptInfo.getPtCode());
                        tz.setPtGoodsId(ptInfo.getPtGoodsId());
                        tzPtCodeService.addTz(tz);
                        TzPtCode tz1 = tzPtCodeService.findTzByPtCode(ptCode);
                        ItemDelayed<TzPtCode> orderDelayed = new ItemDelayed<TzPtCode>((long)tz1.getId(), tz1.getAddTime().getTime());
                        delayOrderService.addToOrderDelayQueue(orderDelayed);
                        //添加成功后返回团长的团单id和拼团号
                        PtInfo ptInfo2 =  ptInfoService.findTzPtInfoByPtCode(ptCode);
                        jsonResult.setData("添加成功!");
                        jsonResult.setData(ptInfo2);
                    }else {
                        jsonResult.setData("添加失败!");
                        jsonResult.setCode("500");
                    }
                }
            }else{
                jsonResult.setData("未支付，不能开启拼团");
            }

        return jsonResult;
    }


    @PostMapping("/addTyPtInfo")
    @ApiOperation(value="添加团员拼团订单", notes="生成团员订单的时候生成团员记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "PtInfo",
                    value = "拼团订单实体类", required = true,
                    dataType = "com.jye.rseven.user.domain.PtInfo"),
            @ApiImplicitParam(paramType="query",name = "ptCode",
                    value = "团单编号", required = true,
                    dataType = "String")
    })
    public JsonResult addTyPtGoods(PtInfo ptInfo, String ptCode,String status) {
        OrderCodeFactory orderCodeFactory = new OrderCodeFactory();
        String pid = orderCodeFactory.getOrderCode(ptInfo.getUId());
        JsonResult jsonResult = new JsonResult();
        Payment payment = new Payment();
        String type = MyConstants.paymentType.pintuan;
        payment.setStatus(status);
        payment.setType(type);
        payment.setOrderId(ptInfo.getPtGoodsId());
        payment.setUId(ptInfo.getUId());
        payment.setPId(pid);
        payment.setTotalPrice(BigDecimal.valueOf(ptInfo.getPrice()));
        payment.setSubject(ptInfo.getName());

        int num = ptInfoService.findPtNumByPtCode(ptCode);

        if (num < 3){
            if (status.equals(MyConstants.payStatus.paid)){
                if (paymentService.addPay(payment)!=0){
                    ptInfo.setPtOrderCode(orderCodeFactory.getOrderCode(ptInfo.getUId()));
                    ptInfo.setPtCode(ptCode); //在分享链接上附上团单的id
                    int is = MyConstants.ptHeader.follow;
                    ptInfo.setIsHeader(is);
                    int i = ptInfoService.addPtInfo(ptInfo);
                if (i == 1) {
                    ptInfoService.addOnePtNumByNumberAndPtCode(num,ptCode);//更新参团团人数
                    TyPtCode ty = new TyPtCode();
                    ty.setPtStatus(MyConstants.ptStatus.doing);
                    ty.setUId(ptInfo.getUId());
                    ty.setPtCode(ptInfo.getPtCode());
                    tyPtCodeService.addTy(ty);
                    jsonResult.setData("添加成功!");
                    //团员加入成功，查找是该团是否满员，若满员了就则修改团长的endtime为自己的付款时间，并将团元团长表的拼团状况修改成已完成
                    if (num+1 == 3){
                        int type2 = MyConstants.ptStatus.success;
                        tyPtCodeService.updatePtStatus(type2,ptCode);
                        tzPtCodeService.updatePtStatus(type2,ptCode);
                    }

                } else {
                    jsonResult.setData("添加失败!");
                    jsonResult.setCode("500");
                }
            }
        }else {
            jsonResult.setData("未支付，不能参加拼团");
        }
        }else{
            jsonResult.setData("该团人数已满");
        }

        return jsonResult;
    }

    @GetMapping("/findPtInfoById")
    @ApiOperation(value="根据id查看订单", notes="可查看某个订单的情况", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "id",
                    value = "订单id", required = true,
                    dataType = "Integer")
    })
    public JsonResult findPtInfoById(Integer id) {
        JsonResult jsonResult = new JsonResult();
        PtInfo ptInfo = ptInfoService.findPtInfoById(id);
        if (!StringUtils.isEmpty(ptInfo)){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }

    @GetMapping("/findPtInfoByUId")
    @ApiOperation(value="查看当前团的参团人数单", notes="查看当前团的参团人数单，根据id", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "uId",
                    value = "用户id", required = true,
                    dataType = "Integer")
    })
    public JsonResult findPtInfoByUId(Integer uId) {
        JsonResult jsonResult = new JsonResult();
        List<PtInfo> ptInfo = ptInfoService.findPtInfoByUId(uId);
        if (!StringUtils.isEmpty(ptInfo)){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }

    @GetMapping("/findPtNumByPtCode")
    @ApiOperation(value="查看当前团号的参团人数", notes="查看当前团的参团人数单，根据id", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "ptCode",
                    value = "团id", required = true,
                    dataType = "String")
    })
    public JsonResult findPtNumByPtCode(String ptCode) {
        JsonResult jsonResult = new JsonResult();
        int i = ptInfoService.findPtNumByPtCode(ptCode);
        if (i==3){
            jsonResult.setMsg("已达到拼团人数！");
            jsonResult.setData(i);
        }else if (i!=0){
            jsonResult.setMsg("还差"+ (3-i) +"人，可拼团成功");
            jsonResult.setData(i);
        } else{
            jsonResult.setCode("500");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }


    @GetMapping("/findPtByUId")
    @ApiOperation(value="查看用户拼团订单", notes="查看用户订单", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "uId",
                    value = "用户id", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "skip",
                    value = "跳过多少条", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit",
                    value = "限制多少条", required = true,
                    dataType = "Integer"),
    })
    public JsonResult findPtByUId(int uid, int skip, int limit){
        JsonResult jsonResult = new JsonResult();
        List<PtInfo> list = ptInfoService.findPtByUId(uid,skip,limit);
        if (list.size()!=0 ){
            jsonResult.setData(list);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("未查询到记录，查询失败");
        }
        return jsonResult;
    }

    @GetMapping("/findPtById")
    @ApiOperation(value="查找单条订单记录", notes="查找单条订单记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "Id",
                    value = "商品id", required = true,
                    dataType = "Integer"),
    })
    public JsonResult findPtById(int Id){
        JsonResult jsonResult = new JsonResult();
        PtInfo ptInfo = ptInfoService.findPtById(Id);
        if (ptInfo !=null ){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("未查询到记录，查询失败");
        }
        return jsonResult;
    }

    @GetMapping("/findAllPt")
    @ApiOperation(value="查找所有拼团记录", notes="查找所有拼团记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "skip",
                    value = "跳过多少条", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit",
                    value = "限制多少条", required = true,
                    dataType = "Integer"),
    })
    public JsonResult findAllPt(int skip, int limit){
        JsonResult jsonResult = new JsonResult();
        List<PtInfo> ptInfo = ptInfoService.findAllPt(skip, limit);
        if (ptInfo !=null ){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("未查询到记录，查询失败");
        }
        return jsonResult;
    }


    @GetMapping("/findAllPtByGoodsId")
    @ApiOperation(value="根据商品查找所有拼团记录", notes="根据商品id查找所有拼团记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "GoodsId",
                    value = "商品id", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "skip",
                    value = "跳过多少条", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit",
                    value = "限制多少条", required = true,
                    dataType = "Integer"),
    })
    public JsonResult findAllPtByGoodsId(int goodsId,int skip, int limit){
        JsonResult jsonResult = new JsonResult();
        List<PtInfo> ptInfo = ptInfoService.findAllByGoodsId(goodsId,skip, limit);
        if (ptInfo !=null ){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("未查询到记录，查询失败");
        }
        return jsonResult;
    }

    @GetMapping("/findAllPtByPtCode")
    @ApiOperation(value="根据团单编号查找所有拼团记录", notes="根据团单编号查找所有拼团记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "PtCode",
                    value = "商品id", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "skip",
                    value = "跳过多少条", required = true,
                    dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit",
                    value = "限制多少条", required = true,
                    dataType = "Integer"),
    })
    public JsonResult findAllPtByPtcode(String ptCode,int skip, int limit){
        JsonResult jsonResult = new JsonResult();
        List<PtInfo> ptInfo = ptInfoService.findAllByPtCode(ptCode,skip, limit);
        if (ptInfo !=null ){
            jsonResult.setData(ptInfo);
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("未查询到记录，查询失败");
        }
        return jsonResult;
    }
}
